﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using PMS.IRepository;
using PMS.IServices;
using PMS.Models.Base;
using PMS.Repository;
using PMS.Utils;

namespace PMS.Services
{
    public class BaseDictService : IBaseDictService
    {
        IBaseDictRepository _baseDictRepository = new BaseDictRepository();

        #region 公共方法

        public int Add(BaseDict user)
        {
            return _baseDictRepository.Add(user);
        }

        public int Edit(BaseDict user)
        {
            return _baseDictRepository.Edit(user);
        }

        public BaseDict Dtl(int id)
        {
            return _baseDictRepository.Dtl(id);
        }

        public bool IsExists(int id)
        {
            return _baseDictRepository.IsExists(id);
        }

        public int Delete(int id, string deleteBy)
        {
            Hashtable ht = new Hashtable { { "ParentId", id } };
            List<int> Ids = _baseDictRepository.GetList(ht)?.Select(x => x.Id).ToList();
            if (Ids != null)
            {
                _baseDictRepository.Delete(Ids.ToArray(), deleteBy);
            }
            return _baseDictRepository.Delete(id, deleteBy);
        }

        public int Delete(int[] ids, string deleteBy)
        {
            return _baseDictRepository.Delete(ids, deleteBy);
        }

        public List<BaseDict> GetList()
        {
            return _baseDictRepository.GetList();
        }

        public List<BaseDict> GetList(Hashtable ht)
        {
            return _baseDictRepository.GetList(ht);
        }

        #endregion

        #region 扩展方法

        /// <summary>
        /// 添加时 更新上级的IsLeaf=0
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public int AddEditParent(int parentId)
        {
            BaseDict dict = _baseDictRepository.Dtl(parentId);
            //只更新一次 节省资源
            if (dict == null || dict.IsLeaf == 1)
            {
                return 1;
            }
            else
            {
                dict.IsLeaf = 1;
                return _baseDictRepository.Edit(dict);
            }
        }


        public int DeleteEditParent(int parentId)
        {
            Hashtable ht = new Hashtable();
            ht.Add("ParentId", parentId);
            //List<BaseDict> dicts = _baseDictRepository.GetList(ht);
            int counts = _baseDictRepository.GetCount(ht);
            if (counts > 0)
            {
                return 1;
            }
            else
            {
                BaseDict dict = _baseDictRepository.Dtl(parentId);
                dict.IsLeaf = 0;
                return _baseDictRepository.Edit(dict);
            }
        }

        #endregion

    }
}